/* Filename: ./5-server.c
 * Description:
 * Last modified: humble 2020-11-12 10:31:31
 * $ gcc -Wall 5-server.c -o 5-server -levent
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>

#define PORT (2500)
#define BUFFER_SIZE (1024)

static void delay(int ms) { clock_t start = clock(); while(clock() - start < ms); }

static void read_cb(struct bufferevent *bev, void *user_data)
{
    char msg[BUFFER_SIZE] = {'\0'};
    struct evbuffer *input = bufferevent_get_input(bev);
    size_t sz = evbuffer_get_length(input);
    if (sz > 0) {
        bufferevent_read(bev, msg, sz);
        printf("%s\n", msg);
    }
}

static void write_cb(struct bufferevent *bev, void *user_data)
{
    //struct evbuffer *output = bufferevent_get_output(bev);
    //if (evbuffer_get_length(output) == 0) {
    //    printf("Output evbuffer is flushed\n");
    //    bufferevent_free(bev);
    //}
    //delay 1 second
    delay(1000);
    static int msg_num = 1;
    char reply_msg[1000] = {'\0'};
    char *str = "I am a message from server";
    memcpy(reply_msg, str, strlen(str));
    sprintf(reply_msg + strlen(str),"%d", msg_num);
    bufferevent_write(bev, reply_msg, strlen(reply_msg));
    msg_num++;
}

static void event_cb(struct bufferevent *bev, short events, void *user_data)
{
    if (events & BEV_EVENT_EOF) {
        printf("Connection closed\n");
    }
    else if (events & BEV_EVENT_ERROR) {
        printf("Got an error on the connection: %s\n", strerror(errno));
    }

    bufferevent_free(bev);
}

void listen_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *addr, int socklen, void *arg)
{
    printf("Detect an connection\n");
    struct event_base *base = (struct event_base *)arg;

    struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    if (bev == NULL) { fprintf(stderr, "bufferevent_socket_new() failed"); event_base_loopbreak(base); exit(1); }
    bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL);
    bufferevent_enable(bev, EV_READ|EV_WRITE);

    //服务器监听到连接时，给客户端发送第一条消息
    char *reply_msg = "I am a message from server";
    bufferevent_write(bev, reply_msg, strlen(reply_msg));
}

int main(int argc, char **argv)
{
    printf("I am server\n");
#ifdef WIN32
    WSAData wsaData;
    WSAStartup(MAKEWORD(2, 0), &wsaData);
#endif
    struct sockaddr_in laddr;
    memset(&laddr, 0, sizeof(laddr));
    laddr.sin_family = AF_INET;
    laddr.sin_port = htons(PORT);

    struct event_base *base = event_base_new();
    if (base == NULL) { fprintf(stderr, "event_base_new() failed"); exit(1); }

    struct evconnlistener *listener = evconnlistener_new_bind(base, listen_cb, (void *)base,
            LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
            (struct sockaddr*)&laddr, sizeof(laddr));
    if (listener == NULL) { fprintf(stderr, "evconnlistener_new_bind() failed"); exit(1); }

    event_base_dispatch(base); //开始监听//死循环监听 如果集合中没有事件可以监听，则返回

    evconnlistener_free(listener); //释放监听对象listener
    event_base_free(base); //释放集合

    return 0;
}
